package com.ruoyi.ma.utils;

import com.jcraft.jsch.*;
import com.ruoyi.ma.domain.ShellUser;
import com.ruoyi.ma.domain.ShellUserCache;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.InputStream;

/**
 * @author cj
 */
@Slf4j
@Component
public class ShellUtil {

    @Autowired
    ShellUserCache shellUser;


    public String getCommandMsg(String command) {
        String result = "";
        try {
            JSch jsch = new JSch();
            Session session = jsch.getSession(shellUser.getUsername(), shellUser.getHost(), shellUser.getPort());
            session.setPassword(shellUser.getPassword());
            session.setUserInfo(getUserInfo());
            session.connect(30000);
            Channel channel = session.openChannel("exec");
            ((ChannelExec) channel).setCommand(command);
            channel.setInputStream(null);
            ((ChannelExec) channel).setErrStream(System.err);
            InputStream in = channel.getInputStream();
            channel.connect();
            byte[] tmp = new byte[1024];
            while (true) {
                while (in.available() > 0) {
                    int i = in.read(tmp, 0, 1024);
                    if (i < 0) {
                        break;
                    }
                    result = new String(tmp, 0, i);
                    log.debug("SSH command back msg :  {}", result);
                }
                if (channel.isClosed()) {
                    if (in.available() > 0) {
                        continue;
                    }
                    break;
                }
            }
            channel.disconnect();
            session.disconnect();
        } catch (Exception e) {
            log.error("SSH command 执行失败", e);
        }
        return result;
    }


    private UserInfo getUserInfo() {

        return new UserInfo() {
            @Override
            public String getPassphrase() {
                System.out.println("getPassphrase");
                return null;
            }

            @Override
            public String getPassword() {
                System.out.println("getPassword");
                return null;
            }

            @Override
            public boolean promptPassword(String s) {
                System.out.println("promptPassword:" + s);
                return false;
            }

            @Override
            public boolean promptPassphrase(String s) {
                System.out.println("promptPassphrase:" + s);
                return false;
            }

            @Override
            public boolean promptYesNo(String s) {
                System.out.println("promptYesNo:" + s);
                return true;//notice here!
            }

            @Override
            public void showMessage(String s) {
                System.out.println("showMessage:" + s);
            }

        };
    }

}
